package com.p2p.front.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;

import com.p2p.base.exception.BizException;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.Money;
import com.p2p.base.model.P2PRecharge;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.Bank;
import com.p2p.front.service.BankService;
import com.p2p.front.service.RechargeService;
import com.p2p.front.web.form.SelectBankModel;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.facade.AccountTransFacade;
import com.p2p.trans.client.result.AccountQueryResult;
import com.p2p.user.facade.UserQueryFacade;
import com.p2p.user.result.UserQueryResult;

@Controller
public class PaymentController extends BaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(PaymentController.class);

	@Resource
	private AccountTransFacade accountTransFacade;

	@Resource
	private AccountQueryFacade accountQueryFacade;

	@Resource
	private UserQueryFacade remoteUserQueryFacade;

	@Resource
	private BankService bankService;

	@Resource
	private RechargeService p2pRechargeService;

	private static DateFormat dateformat = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	private String sendTime = dateformat.format(Calendar.getInstance()
			.getTime());
	private String orderNO = "1237929939";
	private String orderTime = dateformat.format(Calendar.getInstance()
			.getTime());

	@RequestMapping(value = "/recharge/recharge")
	public String toInputAmount(Model model) {
		List<Bank> bankList = bankService.listAll();
		model.addAttribute("bankList", bankList);
		String userId = super.getCurrentUser().getId();
		AccountQueryResult acccountQueryResult = accountQueryFacade
				.getAccountByUserId(userId);
		if (acccountQueryResult.isSuccess()) {
			model.addAttribute("account", acccountQueryResult.getAccountVO());
		}
		return "recharge/recharge";
	}

	@RequestMapping(value = "/recharge/applyPayment", method = RequestMethod.POST)
	public RedirectView applyPayment(String instCode,
			ModelMap modelMap, SelectBankModel selectBankModel,
			HttpServletRequest request, HttpServletResponse response) {

		/** 页面选择银行卡和输入金额后，跳转到这里 */
		BaseUser user = getCurrentUser();

		String userAccountNo = null;

		UserQueryResult userQueryResult = remoteUserQueryFacade
				.getUserInfoById(user.getId());
		if (userQueryResult.isSuccess()) {
			userAccountNo = userQueryResult.getUserInfoFullVO().getAccountNo();

			if (StringUtils.isBlank(userAccountNo)) {
				modelMap.put("errorMessage", "accountNo no exit");
				/*
				 * return new RedirectView("http://" +
				 * DomainUtils.getPoolPath("user") + "/home/bizError.html",
				 * true, false, true);
				 */
				throw new BizException("account_error", "用户的账户为空");
			}
		} else {
			throw new BizException("account_error", "查询用户的账户失败");
		}

		
		String tradeNo = createOrderNo();
		Double inputOrderAmount = selectBankModel.getOrderAmount();
		// String orderTime =
		// dateformat.format(Calendar.getInstance().getTime());
		if (inputOrderAmount == null || inputOrderAmount <= 0 || inputOrderAmount>1000000) {
			throw new BizException("recharge_error", "充值金额必须大于0，并且小于1百万");
		}
		P2PRecharge p2pRecharge = new P2PRecharge();
		p2pRecharge.setUid(user.getId());
		//TODO
		p2pRecharge.setAid(993L);
		// TODO 改成真实的数据
		if(StringUtils.isBlank(instCode)){
			p2pRecharge.setType("NONE");
		}else{
			p2pRecharge.setType(instCode);
		}
		//TODO
		p2pRecharge.setTradeNo("101");
		p2pRecharge.setTradeAccount(userAccountNo);
		p2pRecharge.setMoney(new Money(inputOrderAmount));
		p2pRecharge.setFee(0.00);
		p2pRecharge.setRemark("线上充值");
		p2pRecharge.setAremark("自动");
		long currentTime = Calendar.getInstance().getTimeInMillis();
		p2pRecharge.setAddTime(currentTime);
		p2pRecharge.setOkTime(currentTime);
		p2pRecharge.setAddIp(getRemoteIp(request));
		p2pRecharge.setUpTime(currentTime);
		p2pRecharge.setUpIp(getRemoteIp(request));
		p2pRecharge.setStatus(P2PRecharge.Status.RECHARGEING.getStatus());
		p2pRechargeService.saveP2PRecharge(p2pRecharge);

		// String orderNo = p2pRecharge.getId().toString();

		String url = BasePropertyConfigurer
				.getContextProperty("p2p.fundsDomain")
				+ "/baofu/recharge/applyPayment.html?id=" + p2pRecharge.getId();
		return new RedirectView(url, true, false, true);
	}

	/**
	 * 订单号的生成逻辑
	 */
	private String createOrderNo() {
		return String.valueOf(Math.round(Math.random() * 90000000 + 10000000));
	}
}
